#! /bin/sh
# PCP QA Test No. 653
# checks pmSetProcessIdentity function in libpcp
#
# Copyright (c) 2012 Red Hat, Inc.  All Rights Reserved.
#
seq=`basename $0`
echo "QA output created by $seq"

# get standard environment, filters and checks
. ./common.product
. ./common.filter
. ./common.check

_cleanup()
{
    $sudo rm -f $tmp.*
    exit $status
}

_filter_err()
{
    pid=$1

    # [Fri Nov 23 11:04:47] username(6802)
    sed \
	-e 's/\[.* [0-9 ][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]\]/[TIMESTAMP]/g' \
	-e "s/$pid/PID/g"
}

_filter_out()
{
    uid=$1

    sed \
	-e "s,$here/src,src,g" \
	-e "s/$uid/as local user/g"
}

_filter_ps()
{
    pid=$1
    uid=$2

    tee -a $seq_full | \
    $PCP_AWK_PROG '
NR == 1	{ if ($2 != "PID") {
	    print "PID not in field 2 of ps output!"
	    exit(1)
	  }
	  if ($1 != "UID" && $1 != "USER") {
	    print "UID/USER not in field 1 of ps output!"
	    exit(1)
	  }
	  if ($8 == "CMD" || $8 == "COMMAND")
	    # Linux-like
	    cmd = 8
	  else if ($11 == "COMMAND")
	    # old-style BSD
	    cmd = 11
	  else {
	    print "CMD (or COMMAND) not in field 8 (or 11) of ps output!"
	    print
	    exit(1)
	  }
	  next
	}
$1 == "'$uid'" && $2 == '$pid' {
	  print "found:",$cmd,$(cmd+1),$(cmd+2),$(cmd+3),$(cmd+4)
	  exit(0)
	}
END	{ exit(1) }'
}

status=1	# failure is the default!
username=`id -u -n`	# me, myself & I
trap "_cleanup" 0 1 2 3 15

# make sure the shell babble after username is terminated goes elsewhere
#
exec 2>$tmp.err

# real QA test starts here
echo "== failing case, should error out" | tee -a $seq_full
$here/src/username nosuchuser >$tmp.out 2>&1 &
pid=$!
sleep 1	# give it a chance to start
$PCP_PS_PROG $PCP_PS_ALL_FLAGS | _filter_ps $pid nosuchuser
$sudo $PCP_BINADM_DIR/pmsignal -a username
wait $pid
[ -s $tmp.out ] && cat $tmp.out | _filter_err $pid

echo "== passing case, should be local user" | tee -a $seq_full
$here/src/username $username &
pid=$!
sleep 1	# give it a chance to start
$PCP_PS_PROG $PCP_PS_ALL_FLAGS | _filter_ps $pid $username >$tmp.out
$sudo $PCP_BINADM_DIR/pmsignal -a username
wait $pid
[ -s $tmp.out ] && cat $tmp.out | _filter_out $username

echo >>$seq_full
echo "==== shell's stderr ===========" >>$seq_full
cat $tmp.err >>$seq_full

status=0
exit
